package com.csxy.six.controller;

import com.csxy.six.entity.Material;
import com.csxy.six.service.MaterialService;
import com.csxy.six.service.OssService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/material")
@Tag(name = "学习资料管理", description = "课程资料上传下载接口")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private OssService ossService;

    @Operation(summary = "上传资料", description = "上传学习资料到OSS并保存元数据")
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public String uploadMaterial(
            @Parameter(
                    description = "文件",
                    required = true,
                    content = @Content(mediaType = "application/octet-stream",
                            schema = @Schema(type = "string", format = "binary"))
            )
            @RequestPart("file") MultipartFile file,

            @Parameter(description = "资料标题", required = true)
            @RequestParam("title") String title,

            @Parameter(description = "资料描述", required = true)
            @RequestParam("description") String description,

            @Parameter(description = "标签(逗号分隔)", required = true)
            @RequestParam("tags") String tags,

            @Parameter(description = "上传者ID", required = true)
            @RequestParam("uploaderId") Long uploaderId) {

        String fileUrl = ossService.uploadFile(file);

        Material material = new Material();
        material.setTitle(title);
        material.setDescription(description);
        material.setTags(tags);
        material.setUploaderId(uploaderId);
        material.setFileUrl(fileUrl);
        material.setUploadTime(new Date());
        material.setDownloadCount(0);

        materialService.save(material);
        return fileUrl;
    }

    @Operation(summary = "按标签查询", description = "根据标签查询相关资料")
    @GetMapping("/tag/{tag}")
    public List<Material> getByTag(
            @Parameter(description = "标签名称", required = true)
            @PathVariable String tag) {
        return materialService.getMaterialsByTag(tag);
    }

    @Operation(summary = "下载资料", description = "记录资料下载行为")
    @PostMapping("/{id}/download")
    public boolean download(
            @Parameter(description = "资料ID", required = true)
            @PathVariable Long id,

            @Parameter(description = "用户ID", required = true)
            @RequestParam Long userId) {
        return materialService.downloadMaterial(id, userId);
    }
}